package com.zeen.wima.common;

import java.util.ArrayList;

import android.os.Message;

import com.zeen.wima.proxy.IObserver;
import com.zeen.wima.proxy.TraceProxy;

public class Tracer implements IObserver {

	public static final int ON_REGISTED = 0;

	public static final int ON_REGIST_FAILED = 1;

	public static final int ON_HAVE_REGISTED = 4;
	
	public static final int ON_SYNC = 2;

	public static final int ON_INTERNAL_ERR = 3;
	
	TraceProxy _proxy;

	LocationMonitor _monitor;

	public Tracer() {

	}

	public void onNotify(int what, Object extr) {
		Message msg = new Message();
		switch (what) {
		case TraceProxy.REGISTED:
			if (String.valueOf(extr).equals("0")) {
				msg.what = ON_REGISTED;
			}else if(String.valueOf(extr).equals("3")){
				msg.what = ON_HAVE_REGISTED;
			} else {
				msg.what = ON_REGIST_FAILED;
			}
			notifyViews(msg);
			break;
		case TraceProxy.INTERNAL_ERR:
			msg.what = ON_INTERNAL_ERR;
			notifyViews(msg);
			break;
		case TraceProxy.SYNCD:
			msg.what = ON_SYNC;
			notifyViews(msg);
			break;
		}
	}

	
	ArrayList<IView> _observers = new ArrayList<IView>();

	/**
	 * 注册observer 视图, 注册的视图会被数据更新后被通知
	 * 
	 * @param v
	 *            , 注册的视图
	 * @return
	 */
	final public boolean register(IView v) {
		synchronized (_observers) {
			if (_observers.indexOf(v) >= 0)
				return false;
			_observers.add(v);
		}
		return true;
	}

	/**
	 * 注销注册的视图
	 * 
	 * @param v
	 * @return
	 */
	final public boolean deregister(IView v) {
		synchronized (_observers) {
			if (_observers.indexOf(v) < 0)
				return false;
			return _observers.remove(v);
		}
	}

	/**
	 * 发送消息通知注册的视图
	 * 
	 * @param m
	 */
	final protected void notifyViews(Message m) {
		synchronized (_observers) {
			for (int i = 0; i < _observers.size(); i++) {
				Message copy = new Message();
				copy.copyFrom(m);
				_observers.get(i).getHandler().sendMessage(copy);
			}
		}
	}

	public void trace() {
		Wima app = Wima.getInstance();
		if (_proxy == null) {
			_proxy = (TraceProxy) app.getProxy(TraceProxy.CLASS);
			_proxy.register(this);
		}
		if (_monitor == null)
			_monitor = new LocationMonitor(app);
		_proxy.logPosition(app.getIMEI(), _monitor.getLocation(),
				_monitor.getMethod());
	}

	
	
	public void setLoginInfo(String loginName, String loginPwd) {
		Wima app = Wima.getInstance();
		if (_proxy == null) {
			_proxy = (TraceProxy) app.getProxy(TraceProxy.CLASS);
			_proxy.register(this);
		}
		_proxy.setPwd(app.getIMEI(), loginName, loginPwd);
	}
}
